package com.atsmart.app.activity;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ResultInfo;
//import com.atsmart.app.receiver.BootBroadcastReceiver;
import com.atsmart.app.receiver.HistoryReceiver;
import com.atsmart.app.service.CheckingService;
import com.atsmart.app.sql.UserImsiSql;
import com.atsmart.app.sql.UserInfoSql;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.atsmart.log.UserLog;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;
/**
 * 
 * @author yhl
 * TODO
 * 2013-9-29上午11:06:19
 * {@link description}
 */
public class LoginActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = LoginActivity.class.getName();
	private Button btnRegister;
	private EditText txtPhone;
	private String phoneNum;
	private TextView txtIMSI;
	private StringBuffer buffer = null;
	private Dialog dialog;
	private Context context;
	private boolean isImSI = true;
	private TextView textView = null;
	private UserInfoSql userInfoSql = null;
	private UserImsiSql userImsiSql = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login_layout);
		context = this;
		
		textView = (TextView) findViewById(R.id.txt1);
		
		userInfoSql = new UserInfoSql();
		userInfoSql.open(BizApp.getInstance().getSqlHelper());
		
		userImsiSql = new UserImsiSql();
		userImsiSql.open(BizApp.getInstance().getSqlHelper());
		
		dialog = DialogUtil.getLoadingDialog(context);
		String string = "";
		buffer = new StringBuffer();
		
		if(PrefsUtils.getIsImsi() == null || StringUtil.isEmptyOrNull(PrefsUtils.getIsImsi())){
			isImSI = true;
		}else{
			isImSI = false;
		}
		
		if (!isImSI) {
			textView.setText("您的设备对应的IMEI号为：");
		} 
		
		if (userInfoSql == null || userImsiSql == null || StringUtil.isEmptyOrNull(userInfoSql.getAttribute())
				|| StringUtil.isEmptyOrNull(userImsiSql.getAttribute())
				|| !userImsiSql.getAttribute().equals(
						BizApp.getInstance().getIMSI())) {
			btnRegister = (Button) findViewById(R.id.btn_register);
			txtPhone = (EditText) findViewById(R.id.txt_phone);
			 
			txtIMSI = (TextView) findViewById(R.id.txt_imsi1);
			btnRegister.setOnClickListener(this);
			txtIMSI.setText(BizApp.getInstance().getIMSI());
		} else {
			try{
				if ((BizApp.getInstance().isWiFiActive() || BizApp.getInstance().isNetworkAvailable())&&BizApp.getInstance().keeping) {
					getUpInfo();
					if (buffer != null && buffer.length() > 0)
						string = buffer.deleteCharAt(buffer.length() - 1)
								.toString();
				}
			}catch (Exception e) {
			}
			
			Intent intent = new Intent();
			intent.setClass(this, NavActivity.class);
			intent.putExtra("updata_info", string);
			if(dialog.isShowing()){
				dialog.cancel();
			}
			startActivity(intent);
			Intent i = new Intent(getApplicationContext(),
					CheckingService.class);
			i.putExtra("isfromlogin", "1");
			startService(i);
			this.finish();
		}
	}
 
	
	private void getUpInfo() {

		if (BizApp.getInstance().isWiFiActive()
				|| BizApp.getInstance().isNetworkAvailable()) {
			new ServiceAsynTask<UpdataListInfo>() {

				@Override
				protected UpdataListInfo callService() throws IOException,
						JsonParseException, AssertionError, BizException,
						Exception {
					UpDataInfo dataInfo = new UpDataInfo();
					return ServiceHelper.getInstance().postData(
							ServiceHost.getUpdataInfo(),
							new Gson().toJson(dataInfo), UpdataListInfo.class);
				}

				@Override
				protected void runWithResult(UpdataListInfo result)
						throws Exception {
					if (result != null && result.getItems() != null && result.getItems().size() > 0) {
						for (int i = 0; i < result.getItems().size(); i++) {
							buffer.append(result.getItems().get(i).getFlag()
									+ ",");
						}
					}
				}
				@Override
				protected void runWithError(UpdataListInfo result,
						int iErrorCode) throws Exception {
					if(PrefsUtils.getURL().equals(StringUtil.URL1)){
						PrefsUtils.setURL(StringUtil.URL2);
					}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
						PrefsUtils.setURL(StringUtil.URL1);
					}
					try {
						getUpInfoByUrl2();
					} catch (Exception e) {
					}
				}
			}.execute();
		} 
	}

	private void getUpInfoByUrl2() {

		if (BizApp.getInstance().isWiFiActive()
				|| BizApp.getInstance().isNetworkAvailable()) {
			new ServiceAsynTask<UpdataListInfo>() {

				@Override
				protected UpdataListInfo callService() throws IOException,
						JsonParseException, AssertionError, BizException,
						Exception {
					UpDataInfo dataInfo = new UpDataInfo();
					return ServiceHelper.getInstance().postData(
							ServiceHost.getUpdataInfo(),
							new Gson().toJson(dataInfo), UpdataListInfo.class);
				}

				@Override
				protected void runWithResult(UpdataListInfo result)
						throws Exception {
					if (result != null && result.getItems() != null && result.getItems().size() > 0) {
						for (int i = 0; i < result.getItems().size(); i++) {
							buffer.append(result.getItems().get(i).getFlag()
									+ ",");
						}
					}
				}
				@Override
				protected void runWithError(UpdataListInfo result,
						int iErrorCode) throws Exception {
					if(PrefsUtils.getURL().equals(StringUtil.URL1)){
						PrefsUtils.setURL(StringUtil.URL2);
					}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
						PrefsUtils.setURL(StringUtil.URL1);
					}
				}
			}.execute();
		} 
	}
	
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_register) {
			phoneNum = txtPhone.getText().toString().trim();
			if (StringUtil.isEmptyOrNull(phoneNum)) {
				Toast.makeText(this, "请输入正确的手机号码！", Toast.LENGTH_SHORT).show();
			} else {
				if(BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance().isWiFiActive()){
					login();
				}else{
					Toast.makeText(context, "无可用网络", Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private void login() {
		showLoading();
		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				Phone phone = new Phone();
				phone.phone = phoneNum;
				
				return ServiceHelper.getInstance().postData(
						ServiceHost.getLoginURL(), new Gson().toJson(phone),
						ResultInfo.class);
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				if (result != null) {
					dealWithResult(result);
				}else{
					Message message = new Message();
					message.what = 0x003;
					handler.sendMessage(message);
				}
				hideLoading();
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
//				Message message = new Message();
//				message.what = 0x003;
//				handler.sendMessage(message);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					loginByUrl2();
				}catch (Exception e) {
				}
				hideLoading();
			}
		}.execute();
	}

	private void loginByUrl2() {
		showLoading();
		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				Phone phone = new Phone();
				phone.phone = phoneNum;
				
				return ServiceHelper.getInstance().postData(
						ServiceHost.getLoginURL(), new Gson().toJson(phone),
						ResultInfo.class);
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				if (result != null) {
					dealWithResult(result);
				}else{
					Message message = new Message();
					message.what = 0x003;
					handler.sendMessage(message);
				}
				hideLoading();
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
 
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				Message message = new Message();
				message.what = 0x003;
				handler.sendMessage(message);
				hideLoading();
			}
		}.execute();
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if(msg.what == 0x003){
				Toast.makeText(context, "登陆失败", Toast.LENGTH_SHORT).show();
			} 
		};
	};
	
	@Override
	protected void onResume() {
		super.onResume();
	}

//	private BootBroadcastReceiver installedReceiver = null;
	
	@Override
	protected void onStart() {
		super.onStart();
//		try {
//			installedReceiver = new BootBroadcastReceiver();
//			IntentFilter filter = new IntentFilter();
//			filter.addDataScheme("package");
//			this.registerReceiver(installedReceiver, filter);
//		} catch (Exception e) {
//		}
	}

	@Override
	protected void onDestroy() {
//		if (installedReceiver != null) {
//			this.unregisterReceiver(installedReceiver);
//		}
		super.onDestroy();
	}
	
	private void dealWithResult(ResultInfo resultInfo) {
		if (resultInfo.result == 0) {
			String string = "";
//			Log.e("TAG", "phoneNum; = " + phoneNum);
			try{
				userInfoSql.deleteAttribute();
			}catch (Exception e) {
			}
			userInfoSql.addAttribute(phoneNum);
			try {
				userImsiSql.deleteAttribute();
			} catch (Exception e) {
			}
			userImsiSql.addAttribute(BizApp.getInstance().getIMSI());
			Intent i = new Intent(getApplicationContext(), CheckingService.class);
			i.putExtra("isfromlogin", "1");
			startService(i);
			Intent hisI = new Intent(getApplicationContext(),
					HistoryReceiver.class);
			startService(hisI);
			Intent intent = new Intent();
			intent.setClass(this, NavActivity.class);
			intent.putExtra("updata_info", string);
			if(dialog.isShowing()){
				dialog.cancel();
			}
			startActivity(intent);
			this.finish();
		} else if (resultInfo.result == 1) {
			Toast.makeText(this, "系统中无此手机号", Toast.LENGTH_SHORT).show();
		} else if (resultInfo.result == 2) {
			Toast.makeText(this, "该号码已经注册", Toast.LENGTH_SHORT).show();
		} else if (resultInfo.result == 3) {
			if(PrefsUtils.getIsImsi() == null || StringUtil.isEmptyOrNull( PrefsUtils.getIsImsi())){
				PrefsUtils.setIsImsi("1");
			}else{
				PrefsUtils.setIsImsi(null);
			}
			if(isImSI){
				Toast.makeText(this, "该IMSI已经注册", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, "该IMEI已经注册", Toast.LENGTH_SHORT).show();
			}
		} else if (resultInfo.result == 4) {
			Toast.makeText(this, "该手机号已被注销", Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
		}
	}

	public class Phone implements Serializable {
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("phone")
		public String phone;
	}

	public class UpInfo implements Serializable {

		/**
		 * 2013-7-5下午5:14:30
		 */
		private static final long serialVersionUID = -9203788327524260808L;
		@SerializedName("last-time")
		public String time;
	}

	public class UpDataInfo implements Serializable {

		/**
		 * 2013-7-5下午5:15:16
		 */
		private static final long serialVersionUID = -4543134223274868165L;
		@SerializedName("flag")
		private String flag;

		public String getFlag() {
			return flag;
		}

		public void setFlag(String flag) {
			this.flag = flag;
		}
	}

	public class UpdataListInfo implements Serializable {
		/**
		 * 2013-7-5下午5:15:56
		 */
		private static final long serialVersionUID = -8922855357427189114L;
		@SerializedName("contents")
		private List<UpDataInfo> items;

		public List<UpDataInfo> getItems() {
			return items;
		}

		public void setItems(List<UpDataInfo> items) {
			this.items = items;
		}
	}
}